// lib/services/order_api.dart
import 'package:flutter/material.dart';
import 'package:multi_shop/models/order.dart';
import 'package:multi_shop/models/order_item.dart';
import 'package:multi_shop/network/api_client.dart';

import '../network/api_routes.dart';

class OrderApi {
  final _http = HttpClient();

  /// 提交订单
  Future<Map<String, dynamic>> submit({
    required List<OrderItem> items,
    required int addressId,
    int payMethod = 1,
  }) async {
    return await _http.postJson<Map<String, dynamic>>(ApiRoutes.placeOrder, {
      'items': items,
      'addressId': addressId,
      'payMethod': payMethod,
    });
  }

  /// 订单列表
  Future<List<MallOrder>> list({required int status, int? page = 1}) async {
    final res = await _http.getJson<Map<String, dynamic>>(
      ApiRoutes.orders,
      query: {'status': status, 'page': page},
    );
    // 确保 list 是一个 List
    final list = (res['list'] as List<dynamic>? ?? []);
    return list.map((e) => MallOrder.fromJson(e)).toList();
  }

  /// 订单详情
  Future<MallOrder> detail(String orderNo) async {
    return await _http.getJson<MallOrder>(
      ApiRoutes.orderDetail,
      query: {'orderNo': orderNo},
      convert: (data) => MallOrder.fromJson(data['order']),
    );
  }

  /// 确认收货
  Future<void> confirm(String id) async {
    await _http.postJson<void>(ApiRoutes.updateOrder, {});
  }

  /// 取消订单
  Future<void> cancel(String id) async {
    await _http.postJson<void>(ApiRoutes.updateOrder, {});
  }

  /// 去支付
  Future<Map<String, dynamic>> pay(
    String orderNo,
    int payMethod,
    String password,
  ) async {
    return await _http
        .postJson<Map<String, dynamic>>(ApiRoutes.payOrder, {
          'orderNo': orderNo,
          'payMethod': payMethod,
          'password': password,
        })
        .catchError((err) => {debugPrint("支付请求失败:$err"), throw err});
  }
}
